<template>
  <view class="job-detail-page">
    <!-- 顶部信息栏 -->
    <view class="header-bar">
      <view class="back-btn" @click="goBack">
        <u-icon name="arrow-left" size="32" color="#333"></u-icon>
      </view>
      <view class="header-middle">
        <view class="title-row">
          <text class="job-title">{{job.title}}</text>
        </view>
        <text class="job-location">{{job.city}}</text>
      </view>
      <view class="salary-right">
        <text class="job-salary">{{ setSalary(job.startSalary,job.maxSalary,job.payMethod)}}</text>
      </view>
    </view>

    <!-- 职位信息列表 -->
    <view class="info-list">
      <view class="info-item">
        <text class="info-label">规模</text>
        <text class="info-value">{{job.size}}</text>
      </view>
      <view class="info-item">
        <text class="info-label">行业</text>
        <text class="info-value">{{job.industry}}</text>
      </view>
    </view>
    
    <!-- HR信息标签 -->
    <view class="hr-card">
      <u-avatar :src="job.hr.avatar" size="64" shape="circle"></u-avatar>
      <view class="hr-info">
        <text class="hr-name">{{job.hr.name}}</text>
        <text class="hr-position">{{job.hr.position}} · {{job.hr.company}}</text>
      </view>
    </view>

    <!-- 工作职责（统一格式） -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">工作职责</text>
        <view class="more-btn" @click="toggleDutyExpanded">
          <text class="more-text">{{dutyExpanded ? '收起' : '更多'}}</text>
          <u-icon 
            :name="dutyExpanded ? 'arrow-up' : 'arrow-down'" 
            size="24" 
            color="#07c160"
          ></u-icon>
        </view>
      </view>
      <view class="section-content duty-text" :class="{collapsed: !dutyExpanded}">
        <text>{{job.duty}}</text>
      </view>
    </view>

    <!-- 技能要求 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">技能要求</text>
        <view class="more-btn" @click="toggleExpanded">
          <text class="more-text">{{expanded ? '收起' : '更多'}}</text>
          <u-icon 
            :name="expanded ? 'arrow-up' : 'arrow-down'" 
            size="24" 
            color="#07c160"
          ></u-icon>
        </view>
      </view>
      <view class="section-content skill-text" :class="{collapsed: !expanded}">
        <text>{{job.skill}}</text>
      </view>
    </view>

    <!-- 岗位福利（统一格式） -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">岗位福利</text>
        <view class="more-btn" @click="toggleBenefitExpanded">
          <text class="more-text">{{benefitExpanded ? '收起' : '更多'}}</text>
          <u-icon 
            :name="benefitExpanded ? 'arrow-up' : 'arrow-down'" 
            size="24" 
            color="#07c160"
          ></u-icon>
        </view>
      </view>
      <view class="section-content benefits-content" :class="{collapsed: !benefitExpanded}">
        <view class="benefits-list">
          <view class="benefit-item" v-for="(benefit, index) in job.benefits" :key="index">
            <u-icon name="gift" size="28" color="#ff9f43" class="benefit-icon"></u-icon>
            <text class="benefit-text">{{ benefit }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 公司卡片 -->
    <view class="company-card" @click="goToCompanyDetail">
      <view class="company-header">
        <u-avatar src="/static/logo.png" size="56" shape="circle"></u-avatar>
        <view class="company-info">
          <text class="company-name">{{job.hr.company}}</text>
          <view class="company-tags">
            <text class="company-tag">{{job.companyType}}</text>
            <text class="company-tag">{{job.size}}</text>
          </view>
        </view>
      </view>
      <view class="company-industry">{{job.industry}}</view>
      <view class="company-line">
        <u-icon name="map" size="24" color="#999"></u-icon>
        <text class="company-address">{{job.companyAddress}}</text>
      </view>
	   <view>
	      <view v-if="distance">
	        <text>该企业距您:{{ formatDistance(distance) }}</text>
	      </view>
	    </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <view class="btn-favorite" @click="toggleFavorite">
        <u-icon :name="job.favorite ? 'star-fill' : 'star'" color="#ffb400" size="36"></u-icon>
        <text class="btn-text">{{job.favorite ? '已收藏' : '收藏'}}</text>
      </view>
      <view class="btn-apply">
        <view class="apply-btn" @click="applyJob">
          <text class="apply-text">立即沟通</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
	import {getRecruitAndElse,getJuLi,collectRecruit} from '@/api/user.js'
export default {
  data() {
    return {
		distance:null,
		      locationInfo: null, // 存储经纬度信息
		      address: null, // 存储地址信息
		companyType:'',
		companyAddress:'',
      expanded: false, // 技能要求展开状态
      dutyExpanded: false, // 工作职责展开状态
      benefitExpanded: false, // 岗位福利展开状态
      recruitId: null,
	  userId: null,
      job: {
		  companyId:null,
        title: '',
        payMethod: null,
        startSalary: null,
        maxSalary: null,
        city: '',
        size: '',
        industry: '',
        favorite: false,
        duty: '',
		skill: '',
		benefits: [],
        hr: {
          avatar: '/static/avatar/头像.png',
          name: '',
          position: '',
          company: ''
        }
      }
    }
  },
  onLoad(recruitId) {
    this.recruitId = recruitId.recruitId
	this.userId = recruitId.userId
	this.open()
  },
  methods: {
	  formatDistance(distanceInMeters) {
	      if (typeof distanceInMeters !== 'number' || isNaN(distanceInMeters)) {
	          return '无效距离';
	      }
	      
	      if (distanceInMeters < 0) {
	          return '距离不能为负数';
	      }
	      
	      // 如果距离小于1公里，显示米
	      if (distanceInMeters < 1000) {
	          return "小于一公里";
	      }
	      
	      // 如果距离大于等于1公里，显示公里（保留1位小数）
	      const distanceInKm = distanceInMeters / 1000;
	      
	      // 处理小数部分，避免显示 .0
	      if (distanceInKm % 1 === 0) {
	          return distanceInKm + '公里';
	      } else {
	          return distanceInKm.toFixed(1) + '公里';
	      }
	  },
	  getUserLocation() {
	        uni.getLocation({
	          type: 'wgs84',
	          success: (res) => {
	            this.locationInfo = res;
				getJuLi({lat:this.locationInfo.latitude,lng:this.locationInfo.longitude,companyId:this.job.companyId}).then(res=>{
					if(res.code == 200){
						console.log(res)
						this.distance = res.data
					}
				})
	          }
	        });
	      },
	  open(){
		  getRecruitAndElse({recruitId:this.recruitId,userId:this.userId}).then(res=>{
			  console.log(res)
			  this.job.title = res.data.recruitName
			  this.job.payMethod = res.data.payMethod
			  this.job.startSalary = res.data.startSalary
			  this.job.maxSalary = res.data.maxSalary
			  this.job.city = res.data.parentName + " " + res.data.childName
			  this.job.size = res.data.companyDO.companySize
			  this.job.industry =res.data.industryName
			  this.job.duty = res.data.recruitDetail;
			  this.job.skill = res.data.skillRequest;
			  this.job.favorite = res.data.favorite;
			  this.job.hr.name = res.data.hrDO.hrName;
			  this.job.hr.id = res.data.hrDO.hrId;
			  this.job.hr.position = res.data.hrDO.identity==0?"hr总管":"hr";
			  this.job.hr.company = res.data.companyDO.companyName;
			  this.job.benefits = res.data.welfareInfo.split(/[,，]/);
			  this.job.companyId = res.data.companyDO.companyId;
			  this.job.companyAddress = res.data.companyDO.companyAddress;
			  this.job.companyType = res.data.companyDO.companyType;
			  this.getUserLocation();
		  })
	  },
    setSalary(startSalary, maxSalary, payMethod) {
      if (payMethod === 4) return `面议`;
      const unitMap = ['日', '周', '月', '时'];
      const unit = unitMap[payMethod] || '月';
      if (maxSalary === null) return `${startSalary}/${unit} 起`;
      if (startSalary === null) return `最高 ${maxSalary}/${unit}`;
      return `${startSalary} ~ ${maxSalary}/${unit}`;
    },
    toggleFavorite() {
      uni.showModal({
              title: `${this.job.favorite==false?"收藏":"取消收藏"}`,        // 弹窗标题
              content: `您确定要${this.job.favorite==false?"收藏":"取消收藏"}${this.job.title}吗?`,    // 弹窗说明文字
              confirmText: '确认',       // 确认按钮文字
              cancelText: '取消',        // 取消按钮文字
              confirmColor: '#2979ff',   // 确认按钮颜色（与底部"立即沟通"按钮配色一致）
              cancelColor: '#666',       // 取消按钮颜色
              // 3. 弹窗关闭后的回调（用户点击确认/取消）
              success: (modalRes) => {
				  if (modalRes.confirm) {
					  collectRecruit({recruitId:this.recruitId,userId:this.userId,isNo:this.job.favorite==false?0:1}).then(res=>{
					  		  if(res.code==200){
					  			  this.job.favorite = !this.job.favorite;
					  			  uni.showToast({ title: this.job.favorite ? '收藏成功' : '已取消收藏', icon: 'none' });
					  		  }else{
					  			  uni.showToast({ title: '收藏失败', icon: 'error' });
					  		  }
					  
					  })
				  }
			  }
		})

    },
    goBack() { uni.navigateBack(); },
    toggleExpanded() { this.expanded = !this.expanded; }, // 技能要求展开/收起
    toggleDutyExpanded() { this.dutyExpanded = !this.dutyExpanded; }, // 工作职责展开/收起
    toggleBenefitExpanded() { this.benefitExpanded = !this.benefitExpanded; }, // 岗位福利展开/收起
    applyJob() { uni.navigateTo({ 
		url: `/pages/zj/UserToHRChat?companyId=${this.job.companyId}&hrId=${this.job.hr.id}&hrName=${this.job.hr.name}&companyName=${this.job.hr.company}` }); 
		},
    goToCompanyDetail() { uni.navigateTo({ url: `/pages/zcy/companyDetails?companyId=${this.job.companyId}&userId=${this.userId}` }); }
  }
}
</script>

<style scoped>
	
.job-detail-page {
  padding: 20rpx 20rpx 120rpx;
  background-color: #f7f7f7;
  min-height: 100vh;
}

.header-bar {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  padding: 20rpx 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.back-btn { padding: 15rpx 20rpx; }
.header-middle { flex: 1; padding-right: 20rpx; }
.salary-right { margin-left: auto; padding-right: 30rpx; }
.job-salary { font-size: 32rpx; font-weight: bold; color: #ff6700; }
.title-row { display: flex; align-items: center; margin-bottom: 10rpx; }
.job-title { font-size: 36rpx; font-weight: bold; }
.job-location { font-size: 26rpx; color: #666; }

/* 信息列表 */
.info-list {
  display: flex;
  flex-wrap: wrap;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
}
.info-item { width: 50%; padding: 15rpx 0; display: flex; align-items: center; }
.info-label { font-size: 26rpx; color: #999; margin-right: 15rpx; }
.info-value { font-size: 26rpx; color: #333; font-weight: bold; }

/* HR卡片 */
.hr-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 25rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
}
.hr-info { margin-left: 20rpx; }
.hr-name { font-size: 30rpx; font-weight: bold; display: block; margin-bottom: 8rpx; }
.hr-position { font-size: 26rpx; color: #666; }

/* 统一section样式（工作职责/技能要求/岗位福利） */
.section {
  background-color: #fff;
  margin-bottom: 24rpx;
  padding: 20rpx;
  border-radius: 16rpx;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.section-title { font-size: 30rpx; font-weight: bold; color: #333; }
.more-btn { display: flex; align-items: center; }
.more-text { font-size: 26rpx; color: #07c160; margin-right: 8rpx; }

/* 内容区域统一样式 */
.section-content {
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  white-space: pre-line;
  transition: max-height 0.3s ease;
}
/* 折叠效果（统一控制） */
.collapsed {
  max-height: 240rpx;
  overflow: hidden;
  position: relative;
}
/* 折叠时添加渐变遮罩 */
.collapsed::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60rpx;
  background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,1));
}

/* 岗位福利特有样式 */
.benefits-content {
  padding: 10rpx 0;
  white-space: normal; /* 福利列表不需要pre-line */
}
.benefits-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}
.benefit-item {
  display: flex;
  align-items: center;
  background-color: #fff8e6;
  padding: 12rpx 20rpx;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
}
.benefit-icon { margin-right: 10rpx; }
.benefit-text { font-size: 26rpx; color: #e67e22; }

/* 公司卡片 */
.company-card {
  background-color: #fff;
  padding: 25rpx;
  border-radius: 16rpx;
  margin-top: 30rpx;
}
.company-header { display: flex; align-items: center; margin-bottom: 20rpx; }
.company-info { margin-left: 20rpx; flex: 1; }
.company-name { font-size: 30rpx; font-weight: bold; margin-bottom: 8rpx; }
.company-tags { display: flex; }
.company-tag {
  font-size: 22rpx;
  color: #666;
  padding: 4rpx 16rpx;
  background: #f5f5f5;
  border-radius: 8rpx;
  margin-right: 15rpx;
}
.company-industry { font-size: 26rpx; color: #666; margin-bottom: 15rpx; }
.company-line { display: flex; align-items: center; font-size: 24rpx; color: #666; }
.company-address { margin-left: 8rpx; }

/* 底部操作栏 */
.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}
.btn-favorite {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
}
.btn-text { font-size: 22rpx; color: #666; margin-top: 5rpx; }
.btn-apply { flex: 1; padding: 0 10rpx; }
.apply-btn {
  background-color: #2979ff;
  border-radius: 40rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.apply-text { color: #fff; font-size: 32rpx; font-weight: bold; }
</style>